package com.run.runbbs.controller;

import cn.hutool.core.map.MapUtil;
import com.run.runbbs.Event.EventProducer;
import com.run.runbbs.common.lang.Result;
import com.run.runbbs.entity.Event;
import com.run.runbbs.service.impl.LikeService;
import com.run.runbbs.util.Constant;
import com.run.runbbs.util.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;

@RestController
public class LikeController implements Constant {
    @Autowired
    private LikeService likeService;
    @Autowired
    private JwtUtils jwtUtils;
    @Autowired
    private EventProducer eventProducer;

    @PostMapping("/like")
    public Result like(int entityType, int entityId,int entityUserId,int postId, HttpServletRequest request){
        String jwt=request.getHeader("Authorization");
        int userId=Integer.parseInt(jwtUtils.getClaimByToken(jwt).getSubject());

        //点赞
        likeService.like(userId,entityType,entityId,entityUserId);
        //获取点赞数量
        long likeCount=likeService.findEntityLikeCount(entityType,entityId);
        //状态
        int likeStatus=likeService.findEntityLikeStatus(userId,entityType,entityId);

        //触发点赞事件（通知）
        if(likeStatus==1){
            Event event=new Event()
                    .setTopic(TOPIC_LIKE)
                    .setUserId(userId)
                    .setEntityType(entityType)
                    .setEntityId(entityId)
                    .setEntityUserId(entityUserId)
                    .setData("postId",postId);
            if(event.getEntityUserId()!=userId){
                eventProducer.fireEvent(event);
            }
        }
        return  Result.success(MapUtil.builder()
                .put("likeCount",likeCount)
                .put("likeStatus",likeStatus)
                .map());
    }
    @GetMapping("/getLikeStatus")
    public Result getLikeStatus(int entityType, int entityId, HttpServletRequest request){
        String jwt=request.getHeader("Authorization");
        int userId=Integer.parseInt(jwtUtils.getClaimByToken(jwt).getSubject());
        //获取状态
        int likeStatus=likeService.findEntityLikeStatus(userId,entityType,entityId);
        return  Result.success(MapUtil.builder()
                .put("likeStatus",likeStatus)
                .map());
    }
    @GetMapping("/getUserLikeCount")
    public Result getUserLikeCount(HttpServletRequest request){
        String jwt=request.getHeader("Authorization");
        int userId=Integer.parseInt(jwtUtils.getClaimByToken(jwt).getSubject());

        long userLikeCount=likeService.findUserLikeCount(userId);
        return  Result.success(MapUtil.builder()
                .put("userLikeCount",userLikeCount)
                .map());
    }

}
